﻿#include "server.h"
#include "tcpsocket.h"
#include <QHostAddress>
#include <QDebug>

Server::Server(QObject *parent, int port) : QTcpServer(parent)
{
    listen(QHostAddress::Any, port);   //监听当前端口的所有ip
}

void Server::incomingConnection(qintptr socketDescriptor)
{
    //只要有新连接就生成一个新的套接字
    tcpsocket *tcpclientsocket = new tcpsocket(this);
    tcpclientsocket->setSocketDescriptor(socketDescriptor);
    //将新创建的套接字加入到客户端套接字列表中
    tcpclientsocketlist.append(tcpclientsocket);
    //接收到tcpclientsocket发过来的更新界面的信号
    connect(tcpclientsocket, &tcpsocket::updateserver, this, &Server::slotupdateserver);
}

void Server::slotupdateserver(QString msg, int length)
{
    //将这个信号发送给界面
    emit updateserver(msg, length);

    //将收到的信息发送给每个客户端,从套接字列表中找到需要接收的套接字
    for(int i = 0; i < tcpclientsocketlist.count(); i++)
    {
        QTcpSocket *item = tcpclientsocketlist.at(i);
        item->write(msg.toUtf8().data());
    }
}
